<template>
  <div>
    <div :id="id" :style="{ width: width, height: height }"></div>
  </div>
</template>

<script>
import echarts from 'echarts'

require('echarts/theme/macarons')
export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    eChartObj: {
      type: Object,
      default: {}
    },

    width: {
      type: String,
      default: '100%'
    },

    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      myChart: {}
    }
  },
  mounted() {
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resize)
  },
  watch: {
    eChartObj: {
      handler(newVal, oldVal) {
        this.loadEchart()
      },
      deep: true
    }
  },
  methods: {
    resize() {
      this.myChart.resize()
    },
    loadEchart() {
      this.myChart = echarts.init(document.getElementById(this.id))
      this.myChart.setOption({
        grid: {
          right: '70px',
          left: '20px',
          bottom: '20px',
          containLabel: true //自适应
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: this.eChartObj.tag,
          axisLabel: {         //interval设置成 0 强制显示所有标签
            interval: 0,
            // rotate: 20     //可以通过旋转解决标签显示不下的问题
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.eChartObj.data,
            type: 'bar',
            barWidth: '40%',
            itemStyle: {
              color: '#5470c6',
            }
          }
        ]
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
